<template>
<!-- 损益单 -->
  <zsearch v-loading="loading">
      <template #title>
        <span>损益单管理</span>
      </template>
      <template #date>
        <el-date-picker
            class="date-1"
            type="datetime"
            v-model="date"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择日期"
            >
        </el-date-picker>
      </template>
      <template #select>
        <el-radio-group v-model="status" @change="getRadioValue" class="radio-group-1" style="margin: 0" >
        <el-radio-button label="待处理"></el-radio-button>
        <el-radio-button label="完成"></el-radio-button>
        <el-radio-button label="报废"></el-radio-button>
        <el-radio-button label="不通过"></el-radio-button>
      </el-radio-group>
      </template>
      <template #btns>
        <el-button class="btn-1" @click="hanledSearch" v-jurisdiction="'warehouse:plOrder:orderPage'">查询</el-button>
			  <!-- <el-button class="btn-2">导出</el-button> -->
			  <el-button class="btn-2" @click="handleClickDrawer" v-jurisdiction="'warehouse:plOrder:addOrder'">新建</el-button>
      </template>
      <template #table>
        <ztable 
          :tableData='data' 
          :strucs='groupData'
          @handleRowDblClick="handleRowDblClick"
          :height="'100%'"
          :isshowOperation="true"
        >
        <template #default="slotScope">
          <el-button type="text" class="operation" @click="goDetails(slotScope.rowData)" v-jurisdiction="'warehouse:plOrder:orderDetail'">详情</el-button>
        </template>
        </ztable>
      </template>
      <template #page>
        <zpage 
            :currentPage="current" 
            :total="total" 
            :pageSize="size"
            @handleSizeChange="handleSizeChange" 
            @handleCurrentChange="handleCurrentChange"
        ></zpage>
      </template>
    </zsearch>

    <zdrawer size="40%" @handleClose="drawer" title="新建损益单" v-model="showDrawer" >
      <template #body>
        <div class="ware-head">
      </div>
      <!-- 动态 -->
      <div class="dynamic flex-wrap">
        <component :is="showWidget(item.type)" class="test" v-for="item in groupDataAdd" :key="item.name" :struc="item"  />
      </div>
        <div class="goods-list">
          <div class="serach-goods">
            <el-input placeholder="请输入物品名称" v-model="goodName" @input="searchGoods" class="input-2">
              <template #append>
                <el-button class="btn-5" @click="goodsSee">物品一览</el-button>
              </template>
            </el-input>
          </div>
          <div class="serach-list">
            <table class="z-table" v-if="isShowTable">
                <thead class="z-thead">
                    <tr>
                        <th>名称</th>
                        <th>常用名</th>
                        <th>品牌</th>
                        <th>规格</th>
                        <th>单位</th>
                        <!-- <th>库存</th> -->
                    </tr>
                </thead>
                <tbody class="z-tbody">
                    <tr v-for="good in list" :key="good.id" @click="addItem(good)">
                        <td>{{good.itemName}}</td>
                        <td>{{good.nickname || '未知'}}</td>
                        <td>{{good.brand}}</td>
                        <td>{{good.specification}}</td>
                        <td>{{good.unit}}</td>
                        <!-- <td>{{good.count}}</td> -->
                    </tr>
                </tbody>
            </table>
            <div v-if="!list.length && isShowTable" class="notData">暂无数据</div>
            
          </div>
          <el-table
            :data="Mockdata"
            border
            style="width: 100%"
            height="450"
            >
            <el-table-column
              v-for="item in MockColumns"
              :show-overflow-tooltip="item.name === 'itemName'? true : false"
              :key="item.name"
              :prop="item.name"
              :label="item.viewName"
              :width="item.name === 'goodCount'? '120': ''"
              >
              <template #default="scope">
                <div v-if="item.name === 'goodCount'" >
                  <el-input-number
                      class="num-btn-small"
                      v-model="scope.row[item.name]" 
                      :max="1000" 
                      ></el-input-number>
                </div>
                <template v-else-if="item.name === 'averagePrice'">
                  <span>￥ {{scope.row[item.name]}}</span>
                </template>
                <div v-else>{{scope.row[item.name]}}</div>
              </template>
            </el-table-column>
              <el-table-column fixed="right" label="操作" width="100">
                <template #default="scope">
                  <el-button
                    @click="del(scope.row, scope.$index)"
                    type="text"
                    size="small"
                    class="btn-text"
                  >删除</el-button>
                  </template>
              </el-table-column>
          </el-table>
        </div>
      </template>
      <template #footer>
        <!-- <span class="drawer-footer-total">合计数量:  {{totalNum || 0}}</span> -->
        <span class="drawer-footer-total">合计金额: ￥ {{totalMoney}}</span>
        <el-button class="btn-2" @click="transientStorage">暂存</el-button>
        <el-button class="btn-1" @click="addWarehous">提交</el-button>
      </template>
    </zdrawer>

    <zdialog v-model="dialogGoodsVisible" @handleClose="goodsClose" >
      <template #body>
        <div class="goods-data-list">
            <table class="goods-table">
                <thead class="goods-thead">
                    <tr>
                        <th>名称</th>
                        <th>常用名</th>
                        <th>品牌</th>
                        
                        <th>规格</th>
                        <th>单位</th>
                        <th>库存</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody class="goods-tbody">
                    <tr v-for="good in list" :key="good.id">
                        <td>{{good.itemName}}</td>
                        <td>{{good.nickname || '未知'}}</td>
                        <td>{{good.brand}}</td>
                        <td>{{good.specification}}</td>
                        <td>{{good.unit}}</td>
                        <td>{{good.count}}</td>
                        <td @click="addItem(good)"><el-icon class="btn-color"><right /></el-icon></td>
                    </tr>
                </tbody>
            </table>
            <div v-if="!list.length" class="notData">暂无数据</div>
            
          </div>
      </template>
    </zdialog>
</template>

<script lang='ts'>
import { Right } from '@element-plus/icons-vue'
import { defineComponent, reactive, ref, toRefs, watch } from '@vue/runtime-core'
import ztable from '@components/Table/index.vue'
import zpage from '@components/pagination/pagination.vue'
import zsearch from '@components/search/search.vue'
import zdrawer from "@components/drawer/drawer.vue";
import zdialog from "@components/dialog/dialog.vue"

import useConfgin from '../../hook/getconfig'
import useUser from "../../hook/user";
import { Goodstab } from '../../types/index'
import useRequet, { RespData } from "../../hook/network"
import requestdata from '../../hook/request'
import useShowWidget from "../../components/widget/usechoose";
import { DataStruc } from "../../hook/datastruc";
import { debounce } from "../../utils/debounce"


import { useRouter } from "vue-router"
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'


const ID = 516
export default defineComponent({
  name: 'Allocation',
  components: {
    ztable,
    zpage,
    zsearch,
    zdrawer,
    zdialog,

    Right
  },
  setup() {
    const router = useRouter();
    const {groupData, groupDataAdd, groupDataUpdate} = useConfgin(ID)
    const request = useRequet({ path: "" });

    console.log(groupData)
    console.log('添加', groupDataAdd)

    /** 列表部分 -> 开始 */
    let search = reactive({
      date:'',
      status:'待处理',
      current: 1,
      size: 10,
      total: 0,

      loading: false
    })
    const data = ref([])

    //搜索
    const hanledSearch = () => {
      debounceRefresh()
    }
    
    // 列表 单选按钮
    const getRadioValue = (e: string) => {
      search.status = e
    }
    // 分页
    const handleCurrentChange = (val: number) => {
			search.current = val
      req()
			console.log('handleCurrentChange', val)
		}
    const handleSizeChange = (val: number) => {
      search.size = val
      req()
			console.log('handleSizeChange', val)
		}
    const handleRowDblClick = (row: any) => {
      console.log('进入详情', row.id)
      // let id = row.id
      // let orderIsSelf = row.orderIsSelf
      // router.push({name: 'LossStatementDetails',query:{ id, orderIsSelf }})
    }

    /** 列表部分 -> 结束 */

    const req = () => {
      search.loading = true
      request.sendRequest({
        address: 'warehouse/plOrder/orderPage',
        params: search || {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取损益单失败')
					data.value = resp.data.records
          search.total = resp.data.total
          search.current = resp.data.current

          search.loading = false
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '获取损益单失败')
          
        },
        method: "POST",
      })
    }
    req()

    const debounceRefresh = debounce(req, 1000)



     /** 抽屉部分开始 */
    const showWidget = useShowWidget;
    const user = useUser();
    let isShow = ref(true)
    let isShowTable = ref(false)
    let isUse = ref(true)
    const Mockdata:Goodstab[] = reactive([])
    const MockColumns = [
      {
        name: 'itemName',
        viewName: "名称",
      },
      {
        name: 'brand',
        viewName: "品牌",
      },
      {
        name: 'specification',
        viewName: "规格",
      },
      // {
      //   name: 'count',
      //   viewName: "库存",
      // },
      {
        name: 'goodCount',
        viewName: "数量",
      },
      {
        name: 'averagePrice',
        viewName: "单价",
      },
    ]
    watch(Mockdata, (newValue, oldValue) => {
      goods.totalNum = 0
      goods.totalMoney = 0
      newValue.forEach(item => {
        goods.totalNum += item.goodCount
        goods.totalMoney += Number(item.averagePrice) * Number(item.goodCount)
      })
    })
    let showDrawer = ref(false)
    const Warehouse = reactive({
      type: '',
      id: null,
      options: [] as any
    })
    const supply = reactive({
      supplyTitle:'',
      supplyData: '',
      supplyOptions: [] as any
    })

     // 商品列表类型
    type GoodList = {
      id: string | number,
      nickname: string | number,
      itemName: string,
      brand: string,
      specification: string | number,
      count: string | number,
      goodCount: string | number,
      averagePrice?: string | number,
      unit: string
    }
    const goods = reactive({
      list: [] as GoodList[],
      goodName: '',
      dialogGoodsVisible: false,
      totalNum: 0,
      totalMoney: 0,
      dynamic: [], // 动态
    })


    watch(() => goods.goodName, (newV) => {
      console.log(newV)
      if(newV) {

      } else {
        console.log('空值')
        isShowTable.value = false
      }
    })


    const handleClickDrawer = () => {

      if(temporaryData()) {
        temporaryData()
        console.log('真')
        showDrawer.value = true
      } else {
        console.log(Warehouse.id, '没有暂存数据时')
        showDrawer.value = true
      }

      groupDataAdd.value.forEach((item: DataStruc) => {
        if(item.type === 901) {
          item.value = user.deptName
        }
      })
    }

    const drawerClose = (type: string) => {
      if(type === 'add') {
        showDrawer.value = false
      }
    }
    const cancel = (type: string) => {
      if(type === 'add') {
        showDrawer.value = false
      }
    }

    // 详情
    const goDetails = (rowData: any) => {
      let {id, orderIsSelf} = rowData
          console.log(id)
          router.push({name: 'LossStatementDetails',query:{ id, orderIsSelf }})
    }

    // 得到暂存数据
    const temporaryData = () => {
      let result: any;
      request.sendRequest({
        address: 'warehouse/plOrder/getStaging',
        params: {},
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '失败')
          // ElMessage.success('获取暂存数据成功')
          Mockdata.length = 0

          result = resp.data
          if(result=== null) {
            isUse.value = false
            return
          }

          Warehouse.id = result?.id
          supply.supplyData = result?.supplierId
          if(Array.isArray(resp.data?.details) && resp.data?.details.length > 0) {
            resp.data?.details.forEach((item:any) => {
              Mockdata.push(item)
            })
          } else {
            isUse.value = false
          }
          
          groupDataAdd.value.forEach((item: DataStruc) => {
            if(item.name === "orderTime") {
              item.value = result?.orderTime
            } else if (item.name === "orderUserId") {
              item.value = result?.orderUserId
            }
          })

          console.log(resp.data,' 暂存成功', Mockdata)
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '失败')
          
        },
        method: "GET",
      })

      return result
    }

    // 得到物品数据
    const goodsList = () => {
      request.sendRequest({
        address: 'warehouse/getGoodPage',
        params: {
          name: goods.goodName
        },
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          goods.list = resp.data.records
          console.log(resp.data)
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg)
          
        },
        method: "POST",
      })
    }
    goodsList()

    const searchGoods = (e: string) => {
        goods.goodName = e
      
      isShowTable.value = true
      goodsList()
    }


    // 添加一项
    const addItem = (data: any) => {
      console.log(data)
      console.log('测试 点击加一项')
      let isADD = Mockdata.find(item => {
        return item.itemId === data.id
      })
      console.log(isADD)
      if(isADD) {
        console.debug('已经选中过该物品')
        isShowTable.value = false
        ElMessage.error('该物品已在列表中')
      } else {
        isShowTable.value = false
        Mockdata.push({
          itemName: data.itemName,
          itemId: data.id,
          brand: data.brand,
          specification: data.specification,
          goodCount: 1,
          realGoodPrice: data.averagePrice,
          averagePrice: data.averagePrice,
        })
      }
      
      console.log(Mockdata)
    }

    // 删除逻辑
    const del = (data:object ,index: number) => {
      console.log(data, index)
      Mockdata.splice(index, 1)
    }

    // 物品一览
    const goodsSee = () => {
      goods.dialogGoodsVisible = true
    }

    // 关闭弹框
    const goodsClose = () => {
      goods.dialogGoodsVisible = false
    }

    // 暂存
    const transientStorage = () => {
      console.debug(Warehouse.id, '暂存')
      let parms: any = {}
      groupDataAdd.value.forEach((item: DataStruc) => {
        if(item.type === 901) return
        parms[item.name] = item.value
      })
      parms.id = Warehouse.id
      parms.details = Mockdata

      request.sendRequest({
        address: 'warehouse/plOrder/staging',
        params: parms,
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '失败')
          ElMessage.success('暂存成功')
          showDrawer.value = false
          console.log(resp.data,' 暂存成功')
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '失败')
          
        },
        method: "POST",
      })
    }

    // 新建损益
    const addWarehous = () => {
      console.log(Mockdata)
      Mockdata.forEach(item => {
        item.sumMoneyShow = item.goodCount * item.averagePrice!
      })
      let parms: any = {}
      groupDataAdd.value.forEach((item: DataStruc) => {
        if(item.type === 901) return
        parms[item.name] = item.value
      })
      parms.id = Warehouse.id
      parms.details = Mockdata

      request.sendRequest({
        address: 'warehouse/plOrder/addOrder',
        params: parms,
        success: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '失败')
          ElMessage.success('新建损益单成功')
          showDrawer.value = false
          req()
          console.log(resp.data,' 新建损益')
        },
        fail: (resp: RespData) => {
          if(resp.code !== 0) return ElMessage.error(resp.msg || '失败')
          
        },
        method: "POST",
      })
    }

     // 离开抽屉 还原数据
    const drawer = (val:boolean) => {
      ElMessageBox.confirm('此操作将关闭窗口, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
				showDrawer.value = val
			}).catch(() => {
					ElMessage({
						type: 'info',
						message: '已取消',
					});
      })

		}
    /** 抽屉部分结束 */

    return {
      groupData,
      groupDataAdd,
      ...toRefs(search),
      data,
      goDetails,
      hanledSearch,
      getRadioValue,
      handleCurrentChange,
      handleSizeChange,
      handleRowDblClick,

      ...toRefs(Warehouse),
      ...toRefs(supply),
      ...toRefs(goods),
      MockColumns,
      showWidget,
      drawer,
      showDrawer,
      handleClickDrawer,
      drawerClose,
      cancel,

      isShow,
      isShowTable,
      Mockdata,

      addItem,
      del,
      searchGoods,
      goodsSee,
      goodsClose,
      transientStorage,
      addWarehous,
      user,

      request,
    }
  }
})
</script>

<style lang="scss" scoped>
.ware-head {
  display: flex;
  flex-direction: row;
  font-size: 14px;
  font-weight: 600;
  padding-bottom: 10px;
  padding-top: 10px;
  border-top: 1px solid $mainColor;
  .ware-type {
    padding-right: 20px;
    
  }
}

.list-head {
  display: flex;
  justify-content: space-around;
  background: $mainColor;
  color: white;
}

.goods-list {
  position: relative;
  padding-bottom: 20px;
  .serach-goods {
    padding: 10px 0 10px 0;
    position: relative;
    display: flex;
    border-top: 1px solid $mainColor;
  }
  .serach-list {
    position: absolute;
    top: 50px;
    left: 0;
    z-index: 999;
    width: 100%;
      .z-table {
        width: 100%;
        border-collapse:collapse;
        border-spacing:0;
        text-align:center;
        background: white;
      .z-thead {
        background: $mainColor;
        color: white;
        
      }
      .z-thead > tr > th {
        padding: 10px;
      }
      
      .z-tbody > tr:hover {
        background: $a9-Color;
      }
    }
  }
}

.goods-data-list {
  border: 1px solid $mainColor;
  border-bottom: 1px solid $mainColor;
  height: 400px;
  overflow-y: scroll;
  .goods-table {
    width: 100%;
    border-collapse:collapse;
    border-spacing:0;
    text-align:center;
    background: white;
  }
  .goods-thead {
    background: $mainColor;
    color: white;
    padding: 10px;
  }
  .border-radius {
    border-top-right-radius: 10px;

  }
  .goods-thead > tr > th {
        padding: 10px;
  }
  & > .goods-tbody {
    height: 300px;
  }
  .goods-tbody > tr {
    border-bottom: 1px solid $a11-Color;
  }
  .goods-tbody > tr:nth-child(2n+1) {
    background: $a2-Color;
  }
  .goods-tbody > tr:hover {
    background: $a2-Color;
  }
  .btn-color {
    font-size: 14px;
    font-weight: 600;
    color: $mainColor;
    cursor: pointer;
  }
}


table td{
  word-break: break-all; 
  word-wrap:break-word;
  padding: 10px;
  font:500 12px Arial
}

.drawer-footer-total {
  font-size: 12px;
  padding-right: 20px;
}

.btn-text {
  color: $mainColor;
}

.dynamic {
  padding: 5px 0;
}

</style>